<template>
  <div class="whole_m">
    <div class="playBackView" v-if="courseDetail.pic">
      <play-video
        :getVideoData='playingMedia'
        :coverImg="courseDetail.pic"
        :showPlayBtn="mediaList.length > 0 ? true : false"
        :hasBuy="courseDetail.hasBuyInt"
        :isFreeWatch="firstResourceIsFree"
        @playBtnClick="playBtnClick"
      />
    </div>

    <div :style="{height: videoH + 'px'}"></div>

    <div id="infoView">
      <course-info :courseDetail="courseDetail" :course-remarks="courseRemarks"></course-info>
    </div>

    <div v-if="tabs.length > 0">
      <div v-if="tabBarFix == true" style="height: 45px">
      </div>
      <div :class="tabBarFix == true ? 'tabBar_fix' : ''" :style="{top: videoH + 'px'}">
        <TabBar :tabBarNames="tabs" @tabBarChange="onTabBarChange" :selectedIndex='tabBarIndex'></TabBar>
      </div>
      <div>
        <!----课程详情---->
        <div v-if="tabs[tabBarIndex].name == '课程详情'">
          <image-list-component :img-list="courseRemarks"></image-list-component>
        </div>
        <!----课程播放---->
        <div v-if="tabs[tabBarIndex].name == '课表'">
          <class-schedule :dataList='mediaList' :playing-media="playingMedia" @videoData="playMedia"></class-schedule>
        </div>

        <!----文档---->
        <div v-if="tabs[tabBarIndex].name == '文档'">
          <class-doc :dataList='docList' :courseDetail="courseDetail"/>
        </div>

        <!----测试----->
        <div v-if="tabs[tabBarIndex].name == '课后考核'">
          <class-test :dataList='examTotalList' :courseDetail="courseDetail"/>
        </div>
        <!----AI模拟演练----->
        <div v-if="tabs[tabBarIndex].name == 'AI模拟演练'">
          <voice-list :dataList='voiceList' :courseDetail="courseDetail"/>
        </div>
      </div>
    </div>

    <div v-if="false">
      <div v-if="courseDetail.orgLevelId != 0 && courseDetail.orgLevelId" @click="levelUp">
        <!-- 等级限制的课程 并且未购买 -->
        <div style="height: 45px;"></div>
        <!--普通课程-->
        <div class="info_btn">升级到{{ level }}企业即可解锁该课程</div>

      </div>
      <div v-else>
        <div style="height: 45px;"></div>
        <div v-if="courseDetail.subjectType == 2">
          <!--协会课程-->
          <div class="info_btn" @click="associationPay">请前往课程页面购买</div>
        </div>
        <div v-else>
          <!--普通课程-->
          <div class="info_btn" @click="payClick">购买课程 ¥ {{ courseDetail.payPersonalNum }}</div>
        </div>
      </div>

    </div>


    <div v-if="false">
      <!-- 买过的 -->
      <!-- 非等级限制的课程 -->
      <div style="height: 45px;"></div>
      <div v-if="courseDetail.orgLevelId == 0 || courseDetail.orgLevelId == null">
        <div class="info_btn" v-if="endTime">课程有效期至{{ endTime }}</div>
      </div>
    </div>

    <van-popup v-model="showPayCover" position="bottom">
      <pay-cover :price="courseDetail.payPersonalNum" @sendCloseCover="closeCover" @sendPayWithType="payWithType"/>
    </van-popup>

  </div>
</template>

<script>
import course_api from '@/repo/api/course_api';
import PlayVideo from './components-m/playvideo/video';
import TabBar from './components-m/tabbar/tabbar';
import ImageListComponent from './ImageListComponent';
import ClassSchedule from './components-m/classschedule/index';
import ClassDoc from './components-m/classdoc/index';
import ClassTest from './components-m/classtest/index';
import VoiceList from './components-m/voicelist/index';
import { Dialog, Popup } from 'vant';
import course, { CourseType } from './course';
import CourseInfo from './components-m/courseinfo/CourseInfo';
import PayCover from './components-m/PayCover';
import { payTool } from '@/utils/payTool';
import OnlineAPI from '../../../repo/api/OnlineAPI';
import levelName from '../../../utils/level_util';
import { formatDate } from '@/utils/format_utils';
import EnterpriseCourseAPI from '../../../repo/api/EnterpriseCourseAPI';
import { isIOS } from '@/utils/util';

Vue.use(Popup);
Vue.use(Dialog);
export default {
  name: 'courseDetail',
  components: {
    PlayVideo,
    TabBar,
    ImageListComponent,
    ClassSchedule,
    ClassDoc,
    ClassTest,
    VoiceList,
    CourseInfo,
    PayCover
  },
  data() {
    return {
      courseId: this.$route.params.courseId,  //地址栏获取courseId
      playingMedia: undefined,      //发送给play video的单条数据。
      courseDetail: {},  //课程详情数据
      videoList: [],//视频数组
      audioList: [],//音频数组
      docList: [], //文档数据
      examList: [],//测试数据
      voiceList: [],//AI模拟演练数据
      examOtherList: [], //练习题及错题库模拟考试
      tabBarIndex: 0,

      videoH: 0,
      tabBarFix: false,
      showPayCover: false,
      firstResourceIsFree: false,

      //特定课程的课程详情图片
      courseRemarks: [],
      subjectHuidaoContainUrl: ''
    };
  },
  created() {
    window.onpageshow = function (e) {
      if (e.persisted || (window.performance && window.performance.navigation.type === 2)) {
        window.location.reload();
      }
    };

    this.getCourseData();
    this.getExamsBySubjectId();
  },
  mounted() {

    window.onpageshow = function (e) {
      if (e.persisted || (window.performance && window.performance.navigation.type === 2)) {
        window.location.reload();
      }
    };

    // verifyOrder(this.$route.query.prepay_id)
    this.videoH = document.documentElement.clientWidth * 9 / 16.0;
    window.addEventListener('scroll', this.handleScroll, true);

    window['onJsLinkHuiDao'] = (jsonStr) => {
      this.onJsLinkHuiDao(jsonStr);
    };

    window['jsGetSalesCallBack'] = (jsonStr) => {
      this.jsGetSalesCallBack(jsonStr);
    };

  },
  watch: {
    mediaList(nVal) {
      this.playingMedia = nVal[0];
      if (this.playingMedia) this.playingMedia.subjectTitle = this.courseDetail.title;
    }
  },
  computed: {
    tabs() {
      let tabBars = [];
      if (this.courseRemarks.length > 0) tabBars.push({ name: '课程详情' });
      if (this.videoList.length > 0 || this.audioList.length > 0) tabBars.push({ name: '课表' });
      if (this.docList.length > 0) tabBars.push({ name: '文档' });
      if (this.examTotalList.length > 0) tabBars.push({ name: '课后考核' });
      if (this.voiceList > 0) tabBars.push({ name: 'AI模拟演练' });
      return tabBars;
    },
    mediaList() {
      let list = [...this.videoList, ...this.audioList];
      let result = course.getMediaListByCourseList(list, this.courseDetail.pic);

      if (result[0]) {
        this.firstResourceIsFree = result[0].type === 1;
      }
      return result;

    },
    //测评列表汇总
    examTotalList() {
      return this.examList.concat(this.examOtherList);
    },
    level() {
      return levelName(this.courseDetail);
    },
    endTime() {
      if (this.courseDetail.endTimeLong && this.courseDetail.endTimeLong != 0) {
        let endTime = new Date(this.courseDetail.endTimeLong);
        return formatDate(endTime, 'YYYY年MM月DD日');
      }
      return '';
    },
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll);
    window.onpageshow = () => {

    };
  },
  methods: {
    getExamsBySubjectId() {
      course_api.getExamsBySubjectId(this.courseId).then((result) => {
        // compatible with old/preview tests
        this.examOtherList = result.responseData.list;
      }).catch((e) => {
        console.error(e);
      });
    },
    //播放按钮点击
    playBtnClick(isFirstPlay = false) {
      let media = this.mediaList[0];
      this.playMedia(media, isFirstPlay);
    },
    //播放
    playMedia(media, isFirstPlay = false) {
      //免费播放的视频
      if (!isFirstPlay && !this.$store.getters['memberInfo/isOpen']) return this.$buyMemberPopup();
      media.playCnt += 1;
      this.playingMedia = media;
      this.playingMedia.subjectTitle = this.courseDetail.title;
    },
    //tab切换
    onTabBarChange(index, el) {
      if (el.name === 'AI模拟演练') {
        if (!this.$store.getters['memberInfo/isOpen']) return this.$buyMemberPopup();

        let jumpUrl = this.subjectHuidaoContainUrl + '&referrer=' + encodeURIComponent(window.location.href);
        if (window.hasOwnProperty('zshft')) {
          window.zshft.onJsLinkHuiDao(jumpUrl.toString());
        }

        return;
      }

      this.tabBarIndex = index;
    },
    //监听滚动固定TabBar
    handleScroll() {
      let element = document.getElementById('infoView');
      if (!element) return;

      let elHeight = element.clientHeight;
      let scr = document.documentElement.scrollTop || document.body.scrollTop;
      this.tabBarFix = scr >= elHeight;

    },
    async getCourseData() {
      //动态参数获取特定的课程图片列表
      await OnlineAPI.getParam().then((result) => {
        let dataList = result.pics.courseRemarks || [];
        dataList.forEach((remark) => {
          let courseIdList = remark.courseIds || [];
          if (courseIdList.indexOf(parseInt(this.courseId)) > -1) {
            this.courseRemarks = remark.pics || [];
          }
        });
      });

      await course_api.getSubject(this.courseId).then((res) => {
        this.courseDetail = res.responseData;
      }).catch((error => console.log('error', error)));

      await course.fetchCourseData(this.courseId, CourseType.VIDEO, this.videoList);
      await course.fetchCourseData(this.courseId, CourseType.AUDIO, this.audioList);
      await course.fetchCourseData(this.courseId, CourseType.DOC, this.docList);
      await course.fetchCourseData(this.courseId, CourseType.EXAM, this.examList);

      await EnterpriseCourseAPI.getSubjectHuidaoContainUrl(this.courseId).then((result) => {
        this.voiceList = result.responseData.containLength || 0;
        this.subjectHuidaoContainUrl = result.responseData.subjectHuidaoContainUrl;
      });

    },
    payClick() {
      this.showPayCover = true;
    },
    associationPay() {
      if (this.$route.query.enterStatus) {
        this.$router.go(-1);
      }
    },
    closeCover() {
      this.showPayCover = false;
    },
    // 支付弹窗点击选择支付方式
    payWithType(type) {

      if (window.hasOwnProperty('zshft')) {
        if (isIOS) {
          window.zshft.jsGetSalesCall('jsGetSalesCallBack');
        } else {
          this.showPayCover = false;
          // payTool.buyItem(1, type, this.courseId)
          payTool.aliAddOrderAndInvokePay({ targetId: this.courseId, returnUrl: window.location.href, targetType: 43 });
        }
      }

    },
    jsGetSalesCallBack(callback) {
      let data = typeof callback === 'object' ? callback : JSON.parse(callback);
      if (data) {
        Dialog.confirm({
          message: data.content,
          confirmButtonText: '去联系',
        }).then(() => {
          window.open(`tel://${ data.tellPhone }`);
        });
      }
    },
    levelUp() {
      this.$router.push({ name: 'myOrg' });
    }
  },

};
</script>

<style scoped>
.playBackView {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1;
}

.tabBar_fix {
  position: fixed;
  left: 0;
  right: 0;
  z-index: 1;
}

.go_purchase {
  position: fixed;
  bottom: 0px;
  width: 100%;
  margin: 0 auto;
  height: 45px;
  background: #005BAB;
  text-align: center;
  color: white;
  line-height: 45px;
}

.whole_m {
  background: white;
}

.act-form iframe {
  width: 100%;
  border: none;
  height: 500px;
}

.info_btn {
  position: fixed;
  bottom: 0px;
  width: 100%;
  margin: 0 auto;
  height: 45px;
  background: #1DA1F2;
  text-align: center;
  color: white;
  line-height: 45px;
}
</style>
